'use strict';

const {Controller} = require('egg');
const ResponseUtil = require('../utils/ResponseUtil');
const HelperUtil = require('../utils/HelperUtil');
const StringUtil = require('../utils/StringUtil');
const Constant = require('../config/Constant');
const path = require('path');
const fs = require('fs');

class WechatController extends Controller {


    async MP_verify() {
        const {ctx} = this;
        ctx.type = 'text/plain; charset=utf-8';
        ctx.set('Cache-Control', 'no-cache');
        ctx.body = '1tS0LINY4TFkPf4X'; // 文件里的内容，原封不动
    }

    /*async oauth2Authorize() {
        let code = this.ctx.query.code;

        let host = this.app.config.frontDomain;
        let domain = this.app.config.domain;
        let page = '/oauth2Authorize.vue';
        let REDIRECT_URI = domain + '/courseapp/oauth2/authorize';
        REDIRECT_URI = encodeURIComponent(REDIRECT_URI);

        let WECHAT_CONFIG = this.ctx.service.wechat.getWechatConfig();

        try {

            if (code) {
                const res = await this.ctx.service.wechat.oauth2Authorize(code);
                if (res.token) {
                    this.ctx.redirect(`${host}/${page}&token=${res?.token || ''}&error=${encodeURIComponent(res.error)}`);
                } else {
                    this.ctx.redirect(`${host}/${page}&token=''&error=${encodeURIComponent('授权失败，请稍后再试')}`);
                }
            } else {
                return this.ctx.body = ResponseUtil.success({
                    redirect: `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${WECHAT_CONFIG.APPID}&redirect_uri=${REDIRECT_URI}&response_type=code&scope=snsapi_base&state=123#wechat_redirect`
                });
            }
        } catch (e) {
            this.ctx.app.logger.error(`oauth2Authorize catch error: `, e.message);
            console.error(`oauth2Authorize catch error: `, e.message);
            this.ctx.redirect(`${host}/${page}&token=''&error=${encodeURIComponent('系统错误')}`);
        }

    }*/

    async oauth2Authorize() {
        let host = 'http://192.168.1.24:8080'
        let page = 'home';
        let tokenRes = await this.ctx.service.user.__createToken('123');
        console.log('tokenRes==',tokenRes)
        //this.ctx.redirect(`${host}/${page}?token=${encodeURIComponent(tokenRes.token) || ''}&error=${encodeURIComponent('')}`);
        const redirectUrl = encodeURIComponent(`/oauth2Authorize?token=${tokenRes.token}`);
        this.ctx.redirect(`http://192.168.1.24:8080?redirect=${redirectUrl}`);

    }

}

module.exports = WechatController;
